'use strict';
import React from 'react'
import { View, Text, Image, TouchableOpacity, } from 'react-native'
import { Metrics, Colors, Fonts } from '../Themes'
import { API, WINDOW } from '../Services'
import styles from './Styles/CommonContainerStyles'
import underscore from 'underscore'
import WebView from 'react-native-webview'
import moment from 'moment'

class DevicesChartScreen extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            type: '1',
            theCurrentData: '-',
            maxData: '-',
            minData: '-',
            hourData: [],
            last7daysData: [],
            item: this.props.route.params.item,
            sceneId: this.props.route.params.sceneId,
        }
    }

    componentDidMount() {
        this.fetchData()
    }

    fetchData() {
        API.getEchartsData(this.state.sceneId, this.state.item.sensorType).then((response) => {
            const { resultCode, resultMessage, data } = response
            if (resultCode == 200) {
                let theCurrentData = data.currentData?.val
                let maxData = data.todayData?.minVal
                let minData = data.todayData?.maxVal
                this.setState({ ...data, theCurrentData, maxData, minData })
            } else {
                return WINDOW.showToast(resultMessage)
            }
        })
    }

    _getValue(value, type = this.state.item.sensorType) {
        let firstColor = '#3ACD89'
        let secondColor = '#FCA920'
        let thirdColor = '#EA3767'
        let resultValue
        let resultVColor
        switch (type) {
            case 1:
                if (value >=18 && value <= 23) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if ((value >=8 && value <= 18) || (value >=23 && value <= 28)) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }

                break;
            case 2:
                if (value >=30 && value <= 80) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if ((value >=20 && value <= 30) || (value >=80 && value <= 90)) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 7:
                if (value <= 1000) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=1000 && value <= 2000) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 8:
                if (value <= 0.1) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=0.1 && value <= 0.15) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 12:
                if (value <= 35) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=35 && value <= 75) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 14:
                if (value <= 0.08) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=0.08 && value <= 0.2) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            default:
                break;
        }
        return { resultValue, resultVColor }

    }



    getinjectedJavaScript() {
        console.log(this.state.hourData)
        let xData
        let yData = []
        let chartType = 'line'
        if (this.state.type === '1') {
            chartType = 'bar'
            xData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
            xData.map(() => yData.push(null))
            this.state.hourData.map((element, index) => {
                var normal = new Object
                normal.color = this._getValue(element.avgVal).resultVColor
                var itemStyle = new Object
                itemStyle.normal = normal
                var yjson = new Object
                yjson.value = element.avgVal;
                yjson.itemStyle = itemStyle;
                yData[element.axisVal] = yjson
            })
        } else if (this.state.type === '2') {
            chartType = 'line'
            xData = []
            for (let index = 6; index >= 0; index--) {
                xData.push(moment().subtract(index, "day").format("YYYY-MM-DD"))
            }
            xData.map((element, index) => {
                let data = underscore.find(this.state.last7daysData, (item) => item.axisVal === element)
                if (data) {
                    var normal = new Object;
                    normal.color = this._getValue(element.avgVal).resultVColor
                    var itemStyle = new Object
                    itemStyle.normal = normal
                    var yjson = new Object
                    yjson.value = data.avgVal
                    yjson.itemStyle = itemStyle
                    yData.push(yjson)
                } else {
                    yData.push(null)
                }
            })
        }
        return `
        var yData = ${JSON.stringify(yData)};
        var xData = ${JSON.stringify(xData)};
        var chartType = ${JSON.stringify(chartType)};
        option = {
            tooltip: {},
            xAxis: {
                data: xData,
                splitLine: {
                    show: false,
                },
                axisLine:{
                  lineStyle:{color:'white'}
                  }
            },
            yAxis: {
              splitLine: {
                show: false,
              },
                axisLine: {
                  lineStyle:{color:'white'}
              }
            },
            textStyle:{color:'white'},
            color: ['white'],
            backgroundColor:'transparent',

            series: [{
                type: chartType,
                data: yData,
                barWidth:'20',
            }],
        };
            myChart.setOption(option);
                            `
    }

    _renderWebView() {
        return (
            <View style={{ flex: 1, backgroundColor: 'transparent', marginTop: 0, marginBottom: 15, marginHorizontal: 15, borderRadius: 8 }}>
                <Image source={require('../Images/bg3.png')} style={{ width: '100%', height: '100%', resizeMode: 'stretch', position: 'absolute' }} />
                {Metrics.isIOS ?
                    <WebView
                        ref={(c) => this._webView = c}
                        style={{ backgroundColor: 'transparent' }}
                        source={require('./chart.html')}
                        javaScriptEnabled={true}
                        scrollEnabled={false}
                        originWhitelist={['*']}
                        scalesPageToFit={false}
                        injectedJavaScript={this.getinjectedJavaScript()} /> :
                    <WebView
                        ref={(c) => this._webView = c}
                        style={{ backgroundColor: 'transparent' }}
                        source={{ uri: 'file:///android_asset/chart.html' }}
                        javaScriptEnabled={true}
                        injectedJavaScript={this.getinjectedJavaScript()} />}
            </View>
        )
    }

    _renderHeader = () => {
        return (
            <View>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: 99 }}>
                    <TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{ flexDirection: "row", marginLeft: 40, alignItems: 'center' }}>
                        <Image source={require('../Images/back.png')} />
                        <Text style={{ fontSize: 40, color: 'white', marginLeft: 14 }}>{this.state.item.sensorName}</Text>
                    </TouchableOpacity>
                    <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', borderColor: 'white', borderWidth: 1, borderRadius: 25, marginRight: 40 }}>
                        <TouchableOpacity onPress={() => this.setState({ type: '1' }, () => this._webView.injectJavaScript(this.getinjectedJavaScript()))} style={{ backgroundColor: this.state.type === '1' ? 'white' : 'transparent', width: 170, height: 50, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 25, borderBottomLeftRadius: 25 }} >
                            <Text style={{ fontSize: 20, fontWeight: 'bold', color: this.state.type === '1' ? '#69D9AD' : 'white' }}>24时</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.setState({ type: '2' }, () => this._webView.injectJavaScript(this.getinjectedJavaScript()))} style={{ backgroundColor: this.state.type === '2' ? 'white' : 'transparent', width: 170, height: 50, justifyContent: 'center', alignItems: 'center', borderTopRightRadius: 25, borderBottomRightRadius: 25 }} >
                            <Text style={{ fontSize: 20, fontWeight: 'bold', color: this.state.type === '2' ? '#69D9AD' : 'white' }}>7天</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={{ flexDirection: 'row', height: 0.5, backgroundColor: 'white', marginHorizontal: 40 }} />
            </View>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <Image source={require('../Images/bg.png')} style={{ width: '100%', height: '100%', position: 'absolute' }} resizeMode='stretch' />
                {this._renderHeader()}
                <View style={{ flex: 3, flexDirection: 'row', justifyContent: 'space-between' }}>


                    <View style={{ margin: 40, marginTop: 30, flex: 4 }}>
                        <Text style={{ fontSize: 30, color: 'white'}}>当前值</Text>
                        <View style={{ flexDirection: 'row', alignItems: 'flex-end', marginTop: 5 }}>
                            <Text style={{ fontSize: 120, color: 'white' }}>{this.state.theCurrentData}</Text>
                            <Text style={{ fontSize: 50, color: 'white', marginBottom: 20, marginLeft: 20 }}>{this.state.item.unit}</Text>
                        </View>
                    </View>

                    <View style={{ flex: 5, justifyContent: 'space-between', alignItems: 'center', marginRight: 10, marginTop: 30, marginBottom: 10 }}>
                        <Image source={require('../Images/bg2.png')} style={{ width: '100%', height: '100%', resizeMode: 'stretch', position: 'absolute' }} />
                        <Text style={{ fontSize: 30, color: 'white', marginTop: 30 }}>当前峰值</Text>

                        <View style={{ width: '100%', flexDirection: 'row', backgroundColor: 'clear', marginBottom: 40, justifyContent: 'space-between' }}>

                            <View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 40 }}>
                                <Text style={{ fontSize: 60, color: 'white', marginRight: 10 }}>{this.state.minData}</Text>
                                <View>
                                    <Text style={{ fontSize: 20, color: 'white' }}>最高值</Text>
                                    <Text style={{ fontSize: 20, color: 'white' }}>{this.state.item.unit}</Text>
                                </View>
                            </View>

                            <View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 40 }}>
                                <Text style={{ fontSize: 60, color: 'white', marginRight: 10 }}>{this.state.maxData}</Text>
                                <View>
                                    <Text style={{ fontSize: 20, color: 'white' }}>最低值</Text>
                                    <Text style={{ fontSize: 20, color: 'white' }}>{this.state.item.unit}</Text>
                                </View>
                            </View>

                        </View>


                    </View>
                </View>
                <View style={{ flex: 4, flexDirection: 'row' }}>
                    {this._renderWebView()}
                </View>
            </View>
        )
    }
}

export default DevicesChartScreen
